﻿/*******************************
* author: xxxgggyyy
* date	: 2022-10-31
* desc	: BPT
********************************/
#ifndef BPT_H
#define BPT_H

#include "bpt_node.h"
#include "bpt_inner_node.h"
#include "bpt_leaf.h"
#include <string>
#include <fstream>
#include <mutex>
#include "semaphore.h"

using namespace std;

class BPTree {
	friend class  LockUtil;
private:
	BPTNode* meta_root;
	int branchs;
	int leaf_cap;
	int __size;
	// 为了多线程支持，不使用共享变量
	/*bool insert_ret;
	bool remove_ret;
	bool contain_ret;
	bool load_ret;*/

	// 简单读写互斥
	// 读共享、读写互斥、写写互斥
	int r_count;
	mutex rw_mutex;
	mutex r_count_mutex;
	// 避免写饥饿
	semaphore w_fair_sema;

	void __insert(BPTNode* root, unsigned long, unsigned long, bool&);
	void __remove(BPTNode* root, unsigned long, bool&);
	void __contain(BPTNode* root, unsigned long, bool&);
	void __clear(BPTNode*);

	void __serialize(BPTNode*, ofstream&);
	void __load(BPTNode*&, ifstream&, bool&);

	void __r_entry();
	void __r_leave();
	void __w_entry();
	void __w_leave();

public:
	BPTree(int branchs, int leaf_cap);
	BPTree();
	~BPTree();

	int size() const;
	bool insert(unsigned long, unsigned long);
	bool remove(unsigned long);
	bool contain(unsigned long);
	void clear();
	void print();

	void serialize(const string&);
	bool load(const string&);
};

/*读写锁辅助类，借用自动析构解锁*/
class LockUtil {
private:
	bool __rw;
	BPTree* __bpt;
public:
	LockUtil(BPTree*, bool);
	~LockUtil();
};

#endif